##########################################
## Copyright 2012 Ceruti Francesco
##
##
## This file is part of LiSP (Linux Show Player).
##
## LiSP (Linux Show Player) is free software: you can redistribute it and/or modify
## it under the terms of the GNU Lesser General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## LiSP (Linux Show Player) is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public License
## along with LiSP (Linux Show Player).  If not, see <http://www.gnu.org/licenses/>.
##########################################

import gi
gi.require_version('Gst', '1.0')
import os
import wave
import urllib.request as url
from gi.repository import Gst
from gi.repository import GstPbutils


def getDuration(path):
    ext = extension(path)
    if(ext == '.wav' or ext == '.wave'):
        return waveDuration(path)
    else:
        return gstDuration(path)


def extension(path):
    return os.path.splitext(path)[-1].lower()


def waveDuration(path):
    try:
        f = wave.open(path, 'r')
        frames = f.getnframes()
        rate = f.getframerate()
        f.close()
        return int(frames / float(rate) * 1000)
    except:
        return -1


def gstDuration(path):
    try:
        disc = GstPbutils.Discoverer()
        discInfo = disc.discover_uri('file://' + url.pathname2url(path))
        return int(discInfo.get_duration() / Gst.MSECOND)
    except:
        return -1
